//Pearson Corelation by Nick Topper
//refrenced this page: http://www.stat.wmich.edu/s216/book/node122.html

class pearson {
	public static void main(String[] args) {

	//test case, from: http://www.stat.wmich.edu/s216/book/node122.html
	//should return .866 and some change

	System.out.println("Test Case \n X = {1,3,4,4} \n Y = {2,5,5,8} ");
	
	int[] X = {1,3,4,4};
	int[] Y = {2,5,5,8};
	System.out.print("r = ");
	System.out.println(r(X, Y));
	}
	
	//returns pearson corr-coeff r-value
	public static double r(int[] X, int[] Y) {

	//assuming X and Y are the same length
        int n = X.length;

	//http://www.stat.wmich.edu/s216/book/img307.gif
	double numerator = (sum_XY(X,Y) - ((sum(X,1) * sum(Y,1)) / n));
	double denominator = Math.sqrt( (sum(X,2) - (Math.pow(sum(X,1), 2) / n)) * (sum(Y,2) - (Math.pow(sum(Y,1), 2) / n)) );
	return numerator / denominator;
	}
	
	//sumation of X^n
	private static double sum(int[] X, int n) {
		double sum = 0;
		for(int i =0; i < X.length; i++) {
			sum += Math.pow(X[i], n);
		}
	return sum;
	}

	//summation of X*Y
	private static int sum_XY(int[] X, int[] Y) {
	int sum = 0;
	for(int i =0; i < X.length; i++) {
		sum += X[i] * Y[i];
		}
	return sum;
	}
}
